/**
 * SpringMVC restful 风格
 * 用户控制器，控制关于用户的一些业务逻辑操作
 * @author yanwl
 * @date 2014-10-30
 */
package com.chnbst.bstyun.controller.admin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.chnbst.bstyun.core.common.Pager;
import com.chnbst.bstyun.core.common.SignUtil;
import com.chnbst.bstyun.eos.Eos;
import com.chnbst.bstyun.model.pojo.Order;
import com.chnbst.bstyun.model.pojo.User;
import com.chnbst.bstyun.model.vo.UserVo;
import com.chnbst.bstyun.service.OrderService;
import com.chnbst.bstyun.service.UserService;

/**
 * 控制器注解 请求映射注解
 * controller 代表类是控制器
 * restcontroller 代表类是控制器， 所有的方法 都是ajax方法
 * @author lq
 *
 */
@Controller
@RequestMapping("/sysAdmin")
public class UserAdminController {
	//每页显示的用户数
	private int pageSize = 10;
	//用户列表页码
	private int currPage = 1;
	
	/**
	 * 注入 业务逻辑层
	 */
	@Autowired
	private UserService userService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private Eos eos;
	
	/**
	 * @return 注册用户列表页面
	 * @throws Exception
	 */
	@RequestMapping(value="/userAdmin/userList",method=RequestMethod.GET)
	public ModelAndView userList()throws Exception{
		return new ModelAndView("admin/userManager/userManager");
	}
	
	/**
	 * @return 企业列表页面
	 * @throws Exception
	 */
	@RequestMapping(value="/userAdmin/companyList",method=RequestMethod.GET)
	public ModelAndView companyList()throws Exception{
		return new ModelAndView("admin/userManager/companyManager");
	}
	
	/**
	 * @return 企业员工清单页面
	 * @throws Exception
	 */
	@RequestMapping(value="/userAdmin/companyEmpList/{userId}",method=RequestMethod.GET)
	public ModelAndView companyEmpList(@PathVariable Integer userId)throws Exception{
		ModelAndView mav = new ModelAndView();
		
		UserVo companyInfo = userService.selectUserVoByUserId(userId);
		
		mav.addObject("companyInfo", companyInfo);
		mav.setViewName("admin/userManager/companyEmplManager");
		
		return mav;
	}
	
	/**
	 * Ajax 分页查询注册用户list
	 * @return 注册用户列表页面
	 * @throws Exception
	 */
	@RequestMapping(value="/userAdmin/userList/search",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> userSearch(String page,String last,HttpServletRequest request)throws Exception{
		
		Map<String, Object> map = new HashMap<String, Object>();
		String userName = request.getParameter("userName");
		
		if(SignUtil.isNotEmpty(page)) {
			currPage = Integer.valueOf(page);
		}
		
		if(SignUtil.isNotEmpty(last)) {
			pageSize = Integer.valueOf(last);
		}
		map.put("userEmail", userName);
		map.put("isYun", 1);
		
		int totalRows = userService.selectUserCountByIsYun(map);
		int pageCount = Pager.getPageCount(totalRows, pageSize);
		if(pageCount < currPage) {
			currPage = pageCount;
		}
		int start = Pager.getStart(currPage, pageSize);
		
		map.put("start", start);
		map.put("pageSize", pageSize);
		map.put("sortField", "o.over_time");
		map.put("sortOrder", "desc");
		map.put("groupField", "m.user_id");
		//map.put("isYun", 1);
		
		List<UserVo> userList = userService.selectUsersByIsYun(map);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("page", currPage);
		resultMap.put("pageCount", pageCount);
		resultMap.put("totalRows", totalRows);
		resultMap.put("userList", userList);
		
		return resultMap;
	}
	
	/**
	 * 查询注册用户 注册企业账号列表
	 * @param userId
	 * @return 注册用户注册企业账号列表
	 * @throws Exception
	 */
	@RequestMapping(value="/userAdmin/userCompList/{userId}",method=RequestMethod.GET)
	public ModelAndView userCompList(@PathVariable Integer userId)throws Exception{
		
		ModelAndView mav = new ModelAndView();
		
		User user = userService.selectUserVoByUserId(userId);
		mav.addObject("userInfo", user);
		mav.setViewName("admin/userManager/userCompList");
		
		return mav;
	}
	/**
	 * 根据ID查询单个注册用户的注册企业账号记录
	 * @return 单个注册用户的注册企业账号列表
	 * @throws Exception
	 */
	@RequestMapping(value="/userAdmin/userCompList",method=RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object>  userCompList(Integer userId,String page,String last)throws Exception{
		
		Map<String, Object> map = new HashMap<String, Object>(); 
		
		if(SignUtil.isNotEmpty(page)) {
			currPage = Integer.valueOf(page);
		}
		
		if(SignUtil.isNotEmpty(last)) {
			pageSize = Integer.valueOf(last);
		}
		//map.put("isYun", 0);
		map.put("parentId", userId);
		
		int totalRows = userService.selectUserCountByCondition(map);
		int pageCount = Pager.getPageCount(totalRows, pageSize);
		if(pageCount < currPage) {
			currPage = pageCount;
		}
		int start = Pager.getStart(currPage, pageSize);
		
		map.put("start", start);
		map.put("pageSize", pageSize);
		map.put("sortField","u.user_id");
		map.put("sortOrder", "desc");
		
		List<UserVo> userList = userService.selectUserVoByCondition(map);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("page", currPage);
		resultMap.put("pageCount", pageCount);
		resultMap.put("totalRows", totalRows);
		resultMap.put("userList", userList);
		
		return resultMap;
	}
	
	
	/**
	 * 根据ID查询注册用户单条数据的详细信息
	 * @return 注册用户详情页面
	 * @throws Exception
	 */
	@RequestMapping(value="/userAdmin/userDetail/{userId}",method=RequestMethod.GET)
	public ModelAndView paymentDetail(@PathVariable Integer userId)throws Exception{
		
		ModelAndView mav = new ModelAndView();
		
		//加载用户的详细信息
		UserVo userInfo = userService.selectUserVoByUserId(userId);
		
		mav.addObject("userInfo", userInfo);
		mav.setViewName("admin/userManager/userDetail");
		
		return mav;
	}
	
	/**
	 * Ajax 分页查询企业用户list
	 * @return 企业用户列表页面
	 * @throws Exception
	 */
	@RequestMapping(value="/userAdmin/companyList/search",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> companySearch(String page,String last,HttpServletRequest request)throws Exception{
		
		Map<String, Object> map = new HashMap<String, Object>();
		String isLive = request.getParameter("isLive");
		String userName = request.getParameter("userName");
		
		if(SignUtil.isNotEmpty(page)) {
			currPage = Integer.valueOf(page);
		}
		
		if(SignUtil.isNotEmpty(last)) {
			pageSize = Integer.valueOf(last);
		}
		map.put("isLive", isLive);
		map.put("userEmail", userName);
		map.put("isYun", 0);
		int totalRows = userService.selectUserCountByIsYun(map);
		int pageCount = Pager.getPageCount(totalRows, pageSize);
		if(pageCount < currPage) {
			currPage = pageCount;
		}
		int start = Pager.getStart(currPage, pageSize);
		
		map.put("start", start);
		map.put("pageSize", pageSize);
		map.put("sortField", "o.over_time");
		map.put("sortOrder", "desc");
		map.put("groupField", "m.user_id");
		//map.put("isYun", 0);
		List<UserVo> companyList = userService.selectUsersByIsYun(map);
		
		String countArr = ""; 
		for(int i=0;i<companyList.size();i++){
			String userEmail = companyList.get(i).getCompanyDomainName();
			userEmail = userEmail.replace("www.", "");
			int count = userService.selectCompanyEmpCountByDomain(userEmail);
			if(countArr.equals("")){
				countArr = String.valueOf(count);
			}else{
				countArr = countArr + "|" + String.valueOf(count);
			}
		}
		
		map.put("page", currPage);
		map.put("pageCount", pageCount);
		map.put("totalRows", totalRows);
		map.put("companyList", companyList);
		map.put("countArr", countArr);
		
		return map;
	}
	
	/**
	 * 根据ID查询单条企业用户数据的详细信息
	 * @return 企业用户详情页面
	 * @throws Exception
	 */
	@RequestMapping(value="/userAdmin/companyDetail/{userId}",method=RequestMethod.GET)
	public ModelAndView companyDetail(@PathVariable Integer userId)throws Exception{
		
		ModelAndView mav = new ModelAndView();
		
		UserVo userInfo = userService.selectUserVoByUserId(userId);
		
		mav.addObject("userInfo", userInfo);
		mav.setViewName("admin/userManager/companyDetail");
		
		return mav;
	}
	
	/**
	 * 根据ID查询单条企业用户数据的详细信息
	 * @return 企业用户详情页面
	 * @throws Exception
	 */
	/*@RequestMapping(value="/companyEmplList/{userId}",method=RequestMethod.GET)
	public ModelAndView companyEmplList(@PathVariable Integer userId)throws Exception{
		
		ModelAndView mav = new ModelAndView();
		
		UserVo userInfo = userService.selectUserVoByUserId(userId);
		
		List<UserVo> userVoList = userService.selectCompanyEmpListByDomain(userInfo.getCompanyDomainName().replace("www.", ""));
		
		mav.addObject("userVoList", userVoList);
		mav.setViewName("admin/userManager/companyEmplManager");
		
		return mav;
	}*/
	
	/**
	 * Ajax 分页查询企业用户list
	 * @return 企业用户列表页面
	 * @throws Exception
	 */
	@RequestMapping(value="/userAdmin/companyEmplList",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> companyEmplList(String page,String last,Integer userId)throws Exception{
		UserVo userInfo = userService.selectUserVoByUserId(userId);
		
		if(SignUtil.isNotEmpty(page)) {
			currPage = Integer.valueOf(page);
		}
		
		if(SignUtil.isNotEmpty(last)) {
			pageSize = Integer.valueOf(last);
		}
		
		int totalRows = userService.selectCompanyEmpCountByDomain(userInfo.getCompanyDomainName().replace("www.", ""));
		int pageCount = Pager.getPageCount(totalRows, pageSize);
		if(pageCount < currPage) {
			currPage = pageCount;
		}
		int start = Pager.getStart(currPage, pageSize);
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("start", start);
		map.put("pageSize", pageSize);
		map.put("sortField", "user_id");
		map.put("sortOrder", "desc");
		map.put("userEmail", userInfo.getCompanyDomainName().replace("www.", ""));
		
		List<UserVo> empList = userService.selectCompanyEmpListByDomain(map);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("page", currPage);
		resultMap.put("pageCount", pageCount);
		resultMap.put("totalRows", totalRows);
		resultMap.put("empList", empList);
		
		return resultMap;
	}
	
	/**
	 * 根据ID和userValid修改有效状态（停用、启用企业用户）
	 * @return true 或者false
	 * @throws Exception
	 */
	@RequestMapping(value="/operate/userAdmin/companyUpdateUserValid",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> companyUpdateUserValid(HttpServletRequest request,Integer userId,boolean flag) throws Exception{
		User user = userService.selectUserInfoByUserId(userId);
		boolean isSuccess = false;
		Map<String, Object> map = new HashMap<String, Object>();
		if(flag) {
			//启用用户
			if("0".equals(user.getUserValid())) {
				map.put("message", "用户已经是启动状态，无需启用！！");
			}else {
				user.setUserValid("0");
				isSuccess =  userService.updateUser(user);
				if(isSuccess) {
					String restr = eos.doUser(user.getUserEmail(), flag);
					if(!"ok".equalsIgnoreCase(restr)) {
						isSuccess = false;
						user.setUserValid("1");
						userService.updateUser(user);
						map.put("message", "启用失败，请重新操作！！");
					}
				}else {
					map.put("message", "启用失败，请重新操作！！");
				}
			}
		}else {
			//停用用户
			if("1".equals(user.getUserValid())) {
				map.put("message", "用户已经是停用状态，无需停用！！");
			}else {
				user.setUserValid("1");
				isSuccess =  userService.updateUser(user);
				if(isSuccess) {
					String restr = eos.doUser(user.getUserEmail(), flag);
					if(!"ok".equalsIgnoreCase(restr)) {
						isSuccess = false;
						user.setUserValid("0");
						userService.updateUser(user);
						map.put("message", "停用失败，请重新操作！！");
					}
				}else {
					map.put("message", "停用失败，请重新操作！！");
				}
			}
		}
		map.put("isSuccess", isSuccess);
		return map;
	}

	
	/**
	 * Ajax 根据userID删除企业用户
	 * @return 企业用户列表页面
	 * @throws Exception
	 */
	@RequestMapping(value="/operate/userAdmin/deleteCompany",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> deleteCompany(HttpServletRequest request,Integer userId)throws Exception{
		
		User user = userService.selectUserInfoByUserId(userId);
		boolean isSuccess = false;
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", userId);
		List<Order> order = orderService.selectOrdersByMap(map);
		
		if(order.size() != 0){
			map.put("message", "用户有未完成订单，不能删除！！");
		}else{
			isSuccess = userService.deleteUser(user);
			if(isSuccess) {
				map.put("message", "删除成功！！");
			}else {
				map.put("message", "删除失败！！");
			}
		}
		map.put("isSuccess", isSuccess);
		return map;
	}
	
}
